use axum::extract::Path;

use axum::{
    Json,
    http::StatusCode,
    extract::State,
};
use sqlx::MySqlPool;
use crate::models::table::CreateTable;

pub async fn get_tables(State(pool): State<MySqlPool>) -> Json<Vec<String>> {
    let tables: Vec<String> = sqlx::query!("SHOW TABLES")
        .fetch_all(&pool)
        .await
        .unwrap()
        .into_iter()
        .map(|row| row.Tables_in_your_database_name.unwrap_or(String::new()))
        .collect();
    Json(tables)
}

pub async fn create_table(
    State(pool): State<MySqlPool>,
    Json(payload): Json<CreateTable>,
) -> Result<(), StatusCode> {
    // 将 HashMap 转换为 SQL 列定义
    let columns = payload
        .columns
        .iter()
        .map(|(k, v)| format!("{} {}", k, v))
        .collect::<Vec<_>>()
        .join(", ");

    // 构造完整的 SQL 查询
    let query = format!(
        "CREATE TABLE {} ({})",
        payload.table_name, columns
    );
    println!("{}", query);

    // 执行 SQL 查询
    match sqlx::query(&query).execute(&pool).await {
        Ok(_) => Ok(()),
        Err(e) => {
            eprintln!("Error creating table: {:?}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

pub async fn delete_table(Path(table_name): Path<String>, State(pool): State<MySqlPool>) -> StatusCode {
    let query = format!("DROP TABLE {}", table_name);
    println!("{}", query);
    sqlx::query(&query)
        .execute(&pool)
        .await
        .unwrap();
    StatusCode::NO_CONTENT
}